package com.copro.chemdb.search;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ihelpuoo.util.Pager;

import com.copro.chemdb.ques.QuesUtils;
import com.copro.chemdb.result.Result;
import com.copro.chemdb.result.ResultUtils;
import com.copro.simple.Application;
import com.copro.simple.ScopePager;

import org.ihelpuoo.lang.StringUtils;

public class SearchAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		Application app = Application.me(request);
		Pager pager = Pager.me(request);
		if (null == pager)
			pager = new Pager(1, 20);
		SearchForm sf = (SearchForm) form;

		if(QuesUtils.getChildren(app, sf.getQuesId()).size()>0)
			request.setAttribute("hasChildQues", "true");
		
		String[] ary = StringUtils.splitIgnoreBlank(sf.getKeywords(), " ");

		List<String> keywords = new ArrayList<String>(null == ary ? 0
				: ary.length);
		for (String s : ary) {
			keywords.add(s);
		}

		List<SearchResult> results = SearchUtils.search(app, sf.getQuesId(),
				keywords, pager, sf.getSubjectIds());

		for (Iterator<SearchResult> it = results.iterator(); it.hasNext();) {
			SearchResult sr = it.next();
			if (sr.getParentId() > 0) {
				Result parent = ResultUtils.getResult(app, sr.getParentId());
				sr.setParent(parent);
			}
		}

		request.setAttribute("results", results);
		request.setAttribute("scope", new ScopePager(pager, 10));
		request.setAttribute("keywords", keywords);
		return mapping.findForward("results");
	}
}
